﻿/// -----------------------------------------------------------------
/// DBConnectionHandler.cs: The static class contains methods for obtaining and closing
/// connections to the Database.
/// License: see http://mve.codeplex.com/license; All Rights follows the MS-PL
/// Current owner: shiniwa
/// The project decription: please refer to http://codeplex.com/mve/
/// -----------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;

namespace MVEContentSvc
{
    /// <summary>
    /// This static class contains methods for obtaining and closing
    /// connections to the Database.
    /// Use this class to open and close database connections and data contexts.
    /// </summary>
    internal static class DBConnectionHandler
    {
        /// <summary>
        /// Gets an Open connection to the database using the specified
        /// connectionString.
        /// </summary>
        /// <param name="connectionString">The connectionString to use for the connection.</param>
        /// <returns>An Open SqlConnection connection to the Database.</returns>
        internal static SqlConnection OpenDBConnection(string connectionString)
        {
            try
            {
                SqlConnection connection = new SqlConnection(connectionString);
                connection.Open();

                return connection;
            }
            catch (InvalidOperationException ex)
            {
                ErrorHandler.LogMessage(ex.Message, false);
                throw;
            }
            catch (SqlException ex)
            {
                ErrorHandler.LogMessage(ex.Message, false);
                throw;
            }
        }//end:OpenDBConnection

        /// <summary>
        /// Closes and Disposes a Database connection.
        /// Always use this method to close your Database connections.
        /// </summary>
        /// <param name="connection">The SqlConnection to Close.</param>
        internal static void CloseDBConnection(SqlConnection connection)
        {
            try
            {
                connection.Close();
                connection.Dispose();
            }
            catch (SqlException ex)
            {
                ErrorHandler.LogMessage(ex.Message, false);
                throw;
            }
        }//end:CloseDBConnection
    }
}
